package com.alpsot.spotcheck.activity;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import cn.pda.scan.CardThread;
import cn.pda.scan.ScanThread;
import cn.pda.utils.HfDevice;
import cn.pda.utils.PdaHandler;
import cn.pda.utils.Util;

import com.alpsoft.spotcheck.db.DBManager;
import com.alpsoft.spotcheck.impl.HandleMsg;
import com.alpsoft.spotcheck.model.User;
import com.alpsoft.spotcheck.util.AsyncResponse;
import com.alpsoft.spotcheck.util.DataHelper;
import com.alpsoft.spotcheck.util.FunkeyListener;
import com.alpsoft.spotcheck.util.GlobalVar;
import com.alpsoft.spotcheck.util.SharedPreferencesUtils;
import com.alpsoft.spotcheck.util.UploadDataManager;
import com.alpsot.lkspotcheck.R;
import com.lidroid.xutils.ViewUtils;

/**
 * 程序主页面实现三种点检方式的展现
 *
 * @author Nasir
 */
public class SpotCheckMainActivity extends BaseActivity implements TabListener {

    // 创建日点检
    private DailyCheck dck = new DailyCheck();
    // 创建班点检
    private CheckClazz ckc = new CheckClazz();
    // 创建月点检
    private WeekInspection wis = new WeekInspection();
    /**
     * 定义页签
     */
    private static final int TAB_INDEX_COUNT = 3;
    private static final int TAB_INDEX_ONE = 0;
    private static final int TAB_INDEX_TWO = 1;
    private static final int TAB_INDEX_THREE = 2;
    // 创建ViewPager对象，实现页面滑动
    private ViewPager mViewPager;
    private ViewPagerAdapter mViewPagerAdapter;
    /**
     * 实现数据下载
     */
    // 定义log字符串
    private static final String TAG = "SPOTCHECK_LK";
    // 定义上下文对象
    private Context context;
    // 实现数据处理
    private Intent intent;
    // 定义数据库对象
    private DataHelper dh;
    private DBManager dbManager;
    private SQLiteDatabase db;
    // 功能键广播接收者(按键接收)
    private FunkeyListener receive;
    // 离线登录
    private String noLogin;

    // 记录当前frament值
    private int frament;
    private EditText etScan;
    private boolean supportScan;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spotcheckmain);
        context = this;
        etScan = (EditText) findViewById(R.id.et_scan);
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(etScan.getWindowToken(), 0);
//        // 扫描
//        etScan.setOnKeyListener(new View.OnKeyListener() {
//            @Override
//            public boolean onKey(View view, int keyCode, KeyEvent event) {
//                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
//                    String scanCode = etScan.getText().toString().trim();
//                    etScan.selectAll();
//                    if (TextUtils.isEmpty(scanCode)) {
//                        new AlertDialog.Builder(SpotCheckMainActivity.this)
//                                .setTitle("温馨提示")
//                                .setMessage("条码信息不能为空！")
//                                .create().show();
//                        return true;
//                    }
//                    Message msg = new Message();
//                    msg.what = ScanThread.SCAN;
//                    Bundle bundle = new Bundle();
//                    bundle.putString("data", scanCode);
//                    msg.setData(bundle);
//                    myHandler2.removeMessages(ScanThread.SCAN);
//                    myHandler2.handleMessage(msg);
//                    return true;
//                }
//                return false;
//            }
//        });
// 初始化数据库信息。
        dbManager = DBManager.getInstance(this, GlobalVar.databaseName);
        dh = new DataHelper(this);

        ViewUtils.inject(this);
        // 创建异步下载AsyncTask对象
        DownloadData dld = new DownloadData(context);
        intent = getIntent();
        // 获取登录的方式 离线或者在线
        noLogin = intent.getStringExtra("noLogin");
        // 初始化震动对象
        UserChange();
        Util.initSoundPool(this);
        try {
            String model = Build.MODEL;
            supportScan = model.equalsIgnoreCase(HfDevice.DEV_AX6737) || model.equals(HfDevice.DEV_H901);
        } catch (SecurityException e) {
            e.printStackTrace();
            supportScan = false;
        }
        if (supportScan)
            initSysScan();
        if (noLogin.equals("true")) {
            Toast.makeText(SpotCheckMainActivity.this, "离线使用状态", 5000).show();
            /**
             * 实现页面滑动
             */
            setUpActionBar();
            setUpViewPager();
            setUpTabs();
        } else {
            dld.execute();
            // 利用回调方法获取返回值
            dld.setOnAsyncResponse(new AsyncResponse() {

                @Override
                public void onDataReceivedSuccess(String str) {
                    if (initial(str)) {
                        Toast.makeText(SpotCheckMainActivity.this, "数据处理成功",
                                5000).show();
                        /**
                         * 实现页面滑动
                         */
                        setUpActionBar();
                        setUpViewPager();
                        setUpTabs();
                    }
                }

                @Override
                public void onDataReceivedFailed() {
                    Toast.makeText(SpotCheckMainActivity.this, "数据下载失败，请重新下载", 5000)
                            .show();
                }
            });
        }
    }

    private void initSysScan() {
        receive = new FunkeyListener();
        // 代码注册功能键广播接收者
        IntentFilter filter2 = new IntentFilter();// 定义过滤器
        filter2.addAction("android.intent.action.FUN_KEY");// 添加监听事件:监听功能键
        context.registerReceiver(receive, filter2);// 将上下文环境(容器)定义为事件结果的接收者.
        if ("sc".equals(GlobalVar.scanType)) {
            try {
                GlobalVar.sc = new ScanThread(myHandler2);
            } catch (java.lang.Exception e) {
                e.printStackTrace();
            }
            GlobalVar.sc.start();
        }
    }
    // // 数据上传handler
    // public Handler myHandler = new Handler() {
    // @Override
    // public void handleMessage(Message msg) {
    // switch (msg.what) {
    // case GlobalVar.msg_LoginSuccess:
    // if (dh.hasLocalData()) {// 有数据上传没数据进行跳转
    // UploadDataManager ud = new UploadDataManager(context);
    // ud.checkDataUpInfo("update_dj");
    // }
    // break;
    // case GlobalVar.msg_LoginFailure:
    // Toast.makeText(context, msg.obj.toString(), 2000).show();
    // break;
    // case GlobalVar.msg_UploadSuccess:
    // break;
    // }
    // }
    // };

    // 传递扫码数据 根据相应的frament 处理相应方法
    public PdaHandler myHandler2 = new PdaHandler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case GlobalVar.msg_LoginSuccess:
                    if (dh.hasLocalData()) {// 有数据上传没数据进行跳转
                        UploadDataManager ud = new UploadDataManager(context);
                        ud.checkDataUpInfo("update_dj");
                    } else {
                        if (frament == 0) {
                            msg.obj = "无班点检数据";
                            Toast.makeText(context, msg.obj.toString(), 2000)
                                    .show();
                        } else if (frament == 1) {
                            msg.obj = "无日点检数据";
                            Toast.makeText(context, msg.obj.toString(), 2000)
                                    .show();
                        } else if (frament == 2) {
                            msg.obj = "无周点检数据";
                            Toast.makeText(context, msg.obj.toString(), 2000)
                                    .show();
                        }
                    }
                    break;
                case GlobalVar.msg_LoginFailure:
                    Toast.makeText(context, msg.obj.toString(), 2000).show();
                    break;
                case GlobalVar.msg_UploadSuccess:
                    // 跳转至登录页面
                    Intent intent = new Intent();
                    intent.setClass(context, LoginActivity.class);
                    context.startActivity(intent);
                    break;
                case ScanThread.SCAN:
                    GlobalVar.scanCode = msg.getData().getString("data").trim();
                    etScan.setText(GlobalVar.scanCode);
                    etScan.selectAll();
                    GlobalVar.scanTime = System.currentTimeMillis();
//                    Toast.makeText(getApplicationContext(), GlobalVar.scanCode, Toast.LENGTH_LONG).show();
//                    Log.i("GlobalVar.scanCode ", GlobalVar.scanCode);
                    if (frament == 0) {
                        ckc.getScanEquip();
                    } else if (frament == 1) {
                        dck.getScanEquip();
                    } else if (frament == 2) {
                        wis.getScanEquip();
                    }
                    break;
                case CardThread.READ:// 按下F1,走的是read
                    String data = msg.getData().getString("data");
                    if (null != data) {
                        GlobalVar.scanCode = data.substring(0, 12);
                    }
                    GlobalVar.scanTime = System.currentTimeMillis();
                    msg.obj = ckc.getScanEquip();
                    if (msg.obj != null) {
                        Toast.makeText(context, msg.obj.toString(), 2000).show();
                    }
                    break;
            }
        }
    };

    // 判断用户是否更换
    private void UserChange() {
        User user = SharedPreferencesUtils.getLoginInfo(this);
        // "更换用户",但更换的是个离线(null)用户
        if (noLogin.equals("true")) {// 离线登录:上传数据,加载本地数据库数据

        } else {
            SharedPreferencesUtils.setLoginInfo(context, GlobalVar.user);// 发现更换用户之后,也要把新用户的信息保存
            UploadDataManager ud = new UploadDataManager(context);
            ud.checkDataUpInfo("download_dj");
        }
    }

    // 实现数据处理
    private boolean initial(String str) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("接收数据" + df.format(new Date()).toString());
        dh.clear_dj();
        boolean bool = false;
        JSONObject jsonObject;
        try {
            jsonObject = new JSONObject(str);
            JSONArray eqArray = (JSONArray) jsonObject.get("equipmentList");
            JSONArray itemArray = (JSONArray) jsonObject.get("itemList");
            JSONArray recordArray = (JSONArray) jsonObject.get("recordList");
            JSONArray expArray = (JSONArray) jsonObject.get("exceptionList");
            System.out
                    .println("JSONArray完成" + df.format(new Date()).toString());
            db = dbManager.openDatabase();
            // 写数据到设备表
            StringBuilder sb = new StringBuilder();
            sb.append("insert into EQ_EQUIPMENT VALUES (");
            sb.append("?,?,?,?,?,?,?,?,?,?)");
            insertEquipment(sb.toString(), eqArray);
            // 写数据到点检项目表
            sb = new StringBuilder();
            sb.append("insert into EQ_CHECK_ITEM VALUES (");
            sb.append("?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
            insertCheckItem(sb.toString(), itemArray);
            sb = new StringBuilder();
            sb.append("insert into EQ_CHECK_RECORD VALUES (");
            sb.append("?,?,?,?,?,?,?,?,?,?)");
            insertCheckRecord(sb.toString(), recordArray);
            // 写数据到异常表
            sb = new StringBuilder();
            sb.append("insert into RP_EXCEPTION_SUBMIT ");
            sb.append("(SUBMIT_USER_ID,EQUIPMENT_ID,RESOURCE_ID,SUBMIT_TIME,SUBMIT_CONTENT,STATUS,DX_RESULT,RESOURCE_TYPE,DX_TIME,REMARKS,DX_USER_ID,FLAG) ");
            sb.append(" VALUES ");
            sb.append("(?,?,?,?,?,?,?,?,?,?,?,?)");
            insertException(sb.toString(), expArray);
            db.close();
            System.out.println("保存完成" + df.format(new Date()).toString());
            return bool = true;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return bool;
    }

    /**
     * 插入设备表信息
     *
     * @param sql
     * @param eqList
     */
    public void insertEquipment(String sql, JSONArray eqArray) {// 此处报错:本地表中有13列,可只提供了10values
        SQLiteStatement stat = db.compileStatement(sql);
        db.beginTransaction();
        try {
            for (int i = 0; i < eqArray.length(); i++) {
                if (TextUtils.isEmpty((CharSequence) eqArray.getJSONObject(i)
                        .get("equipmentId"))) {
                    stat.bindNull(1);
                } else {
                    stat.bindString(1,
                            eqArray.getJSONObject(i).get("equipmentId")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) eqArray.getJSONObject(i)
                        .get("deptId"))) {
                    stat.bindNull(2);
                } else {
                    stat.bindString(2, eqArray.getJSONObject(i).get("deptId")
                            .toString());
                }
                if (TextUtils.isEmpty((CharSequence) eqArray.getJSONObject(i)
                        .get("selfCode"))) {
                    stat.bindNull(3);
                } else {
                    stat.bindString(3, eqArray.getJSONObject(i).get("selfCode")
                            .toString());
                }
                if (TextUtils.isEmpty((CharSequence) eqArray.getJSONObject(i)
                        .get("parentCode"))) {
                    stat.bindNull(4);
                } else {
                    stat.bindString(4,
                            eqArray.getJSONObject(i).get("parentCode")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) eqArray.getJSONObject(i)
                        .get("scanCode"))) {
                    stat.bindNull(5);
                } else {
                    stat.bindString(5, eqArray.getJSONObject(i).get("scanCode")
                            .toString());
                }
                if (TextUtils.isEmpty((CharSequence) eqArray.getJSONObject(i)
                        .get("equipmentName"))) {
                    stat.bindNull(6);
                } else {
                    stat.bindString(6,
                            eqArray.getJSONObject(i).get("equipmentName")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) eqArray.getJSONObject(i)
                        .get("createUserId"))) {
                    stat.bindNull(7);
                } else {
                    stat.bindString(7,
                            eqArray.getJSONObject(i).get("createUserId")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) eqArray.getJSONObject(i)
                        .get("equipmentType"))) {
                    stat.bindNull(8);
                } else {
                    stat.bindString(8,
                            eqArray.getJSONObject(i).get("equipmentType")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) eqArray.getJSONObject(i)
                        .get("workStatus"))) {
                    stat.bindNull(9);
                } else {
                    stat.bindString(9,
                            eqArray.getJSONObject(i).get("workStatus")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) eqArray.getJSONObject(i)
                        .get("remark"))) {
                    stat.bindNull(10);
                } else {
                    stat.bindString(10, eqArray.getJSONObject(i).get("remark")
                            .toString());
                }

                stat.executeInsert();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        db.setTransactionSuccessful();
        db.endTransaction();
    }

    /**
     * 插入点检项目表信息
     *
     * @param sql
     * @param ckList
     */
    public void insertCheckItem(String sql, JSONArray itemArray) {
        SQLiteStatement stat = db.compileStatement(sql);
        db.beginTransaction();
        try {
            for (int i = 0; i < itemArray.length(); i++) {
                if (TextUtils.isEmpty((CharSequence) itemArray.getJSONObject(i)
                        .get("checkItemId"))) {
                    stat.bindNull(1);
                } else {
                    stat.bindString(1,
                            itemArray.getJSONObject(i).get("checkItemId")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) itemArray.getJSONObject(i)
                        .get("equipmentId"))) {
                    stat.bindNull(2);
                } else {
                    stat.bindString(2,
                            itemArray.getJSONObject(i).get("equipmentId")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) itemArray.getJSONObject(i)
                        .get("itemCode"))) {
                    stat.bindNull(3);
                } else {
                    stat.bindString(3,
                            itemArray.getJSONObject(i).get("itemCode")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) itemArray.getJSONObject(i)
                        .get("itemContent"))) {
                    stat.bindNull(4);
                } else {
                    stat.bindString(4,
                            itemArray.getJSONObject(i).get("itemContent")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) itemArray.getJSONObject(i)
                        .get("itemCycle"))) {
                    stat.bindNull(5);
                } else {
                    stat.bindString(5,
                            itemArray.getJSONObject(i).get("itemCycle")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) itemArray.getJSONObject(i)
                        .get("itemType"))) {
                    stat.bindNull(6);
                } else {
                    stat.bindString(6,
                            itemArray.getJSONObject(i).get("itemType")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) itemArray.getJSONObject(i)
                        .get("unit"))) {
                    stat.bindNull(7);
                } else {
                    stat.bindString(7, itemArray.getJSONObject(i).get("unit")
                            .toString());
                }
                if (TextUtils.isEmpty((CharSequence) itemArray.getJSONObject(i)
                        .get("downValue"))) {
                    stat.bindNull(8);
                } else {
                    stat.bindString(8,
                            itemArray.getJSONObject(i).get("downValue")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) itemArray.getJSONObject(i)
                        .get("upValue"))) {
                    stat.bindNull(9);
                } else {
                    stat.bindString(9, itemArray.getJSONObject(i)
                            .get("upValue").toString());
                }
                if (TextUtils.isEmpty((CharSequence) itemArray.getJSONObject(i)
                        .get("handleWay"))) {
                    stat.bindNull(10);
                } else {
                    stat.bindString(10,
                            itemArray.getJSONObject(i).get("handleWay")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) itemArray.getJSONObject(i)
                        .get("remarks"))) {
                    stat.bindNull(11);
                } else {
                    stat.bindString(11,
                            itemArray.getJSONObject(i).get("remarks")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) itemArray.getJSONObject(i)
                        .get("lastDate"))) {
                    stat.bindNull(12);
                } else {
                    stat.bindString(12,
                            itemArray.getJSONObject(i).get("lastDate")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) itemArray.getJSONObject(i)
                        .get("cycleUnit"))) {
                    stat.bindNull(13);
                } else {
                    stat.bindString(13,
                            itemArray.getJSONObject(i).get("cycleUnit")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) itemArray.getJSONObject(i)
                        .get("cycleType"))) {
                    stat.bindNull(14);
                } else {
                    stat.bindString(14,
                            itemArray.getJSONObject(i).get("cycleType")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) itemArray.getJSONObject(i)
                        .get("standard"))) {
                    stat.bindNull(15);
                } else {
                    stat.bindString(15,
                            itemArray.getJSONObject(i).get("standard")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) itemArray.getJSONObject(i)
                        .get("itemFn"))) {
                    stat.bindNull(16);
                } else {
                    stat.bindString(16, itemArray.getJSONObject(i)
                            .get("itemFn").toString());
                }
                stat.executeInsert();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        db.setTransactionSuccessful();
        db.endTransaction();
    }

    /**
     * 插入异常表信息
     *
     * @param sql
     * @param expList
     */
    public void insertException(String sql, JSONArray expArray) {
        SQLiteStatement stat = db.compileStatement(sql);
        db.beginTransaction();
        try {
            for (int i = 0; i < expArray.length(); i++) {
                if (TextUtils.isEmpty((CharSequence) expArray.getJSONObject(i)
                        .get("createUserId"))) {
                    stat.bindNull(1);
                } else {
                    stat.bindString(1,
                            expArray.getJSONObject(i).get("createUserId")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) expArray.getJSONObject(i)
                        .get("equipmentId"))) {
                    stat.bindNull(2);
                } else {
                    stat.bindString(2,
                            expArray.getJSONObject(i).get("equipmentId")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) expArray.getJSONObject(i)
                        .get("resourceId"))) {
                    stat.bindNull(3);
                } else {
                    stat.bindString(3,
                            expArray.getJSONObject(i).get("resourceId")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) expArray.getJSONObject(i)
                        .get("submitTime"))) {
                    stat.bindNull(4);
                } else {
                    stat.bindString(4,
                            expArray.getJSONObject(i).get("submitTime")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) expArray.getJSONObject(i)
                        .get("submitContent"))) {
                    stat.bindNull(5);
                } else {
                    stat.bindString(5,
                            expArray.getJSONObject(i).get("submitContent")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) expArray.getJSONObject(i)
                        .get("status"))) {
                    stat.bindNull(6);
                } else {
                    stat.bindString(6, expArray.getJSONObject(i).get("status")
                            .toString());
                }
                if (TextUtils.isEmpty((CharSequence) expArray.getJSONObject(i)
                        .get("dxResult"))) {
                    stat.bindNull(7);
                } else {
                    stat.bindString(7, expArray.getJSONObject(i)
                            .get("dxResult").toString());
                }
                if (TextUtils.isEmpty((CharSequence) expArray.getJSONObject(i)
                        .get("resourceType"))) {
                    stat.bindNull(8);
                } else {
                    stat.bindString(8,
                            expArray.getJSONObject(i).get("resourceType")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) expArray.getJSONObject(i)
                        .get("dxTime"))) {
                    stat.bindNull(9);
                } else {
                    stat.bindString(9, expArray.getJSONObject(i).get("dxTime")
                            .toString());
                }
                if (TextUtils.isEmpty((CharSequence) expArray.getJSONObject(i)
                        .get("remarks"))) {
                    stat.bindNull(10);
                } else {
                    stat.bindString(10, expArray.getJSONObject(i)
                            .get("remarks").toString());
                }
                if (TextUtils.isEmpty((CharSequence) expArray.getJSONObject(i)
                        .get("dxUserId"))) {
                    stat.bindNull(11);
                } else {
                    stat.bindString(11,
                            expArray.getJSONObject(i).get("dxUserId")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) expArray.getJSONObject(i)
                        .get("flag"))) {
                    stat.bindNull(12);
                } else {
                    stat.bindString(12, expArray.getJSONObject(i).get("flag")
                            .toString());
                }
                stat.executeInsert();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        db.setTransactionSuccessful();
        db.endTransaction();
    }

    /**
     * 插入点检记录表信息
     *
     * @param sql
     * @param crList
     */
    public void insertCheckRecord(String sql, JSONArray recordArray) {
        SQLiteStatement stat = db.compileStatement(sql);
        db.beginTransaction();
        try {
            for (int i = 0; i < recordArray.length(); i++) {
                if (TextUtils.isEmpty((CharSequence) recordArray.getJSONObject(
                        i).get("checkRecordId"))) {
                    stat.bindNull(1);
                } else {
                    stat.bindString(1,
                            recordArray.getJSONObject(i).get("checkRecordId")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) recordArray.getJSONObject(
                        i).get("checkItemStrategyId"))) {
                    stat.bindNull(2);
                } else {
                    stat.bindString(
                            2,
                            recordArray.getJSONObject(i)
                                    .get("checkItemStrategyId").toString());
                }
                if (TextUtils.isEmpty((CharSequence) recordArray.getJSONObject(
                        i).get("checkUserId"))) {
                    stat.bindNull(3);
                } else {
                    stat.bindString(3,
                            recordArray.getJSONObject(i).get("checkUserId")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) recordArray.getJSONObject(
                        i).get("checkTime"))) {
                    stat.bindNull(4);
                } else {
                    stat.bindString(4,
                            recordArray.getJSONObject(i).get("checkTime")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) recordArray.getJSONObject(
                        i).get("checkResult"))) {
                    stat.bindNull(5);
                } else {
                    stat.bindString(5,
                            recordArray.getJSONObject(i).get("checkResult")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) recordArray.getJSONObject(
                        i).get("isException"))) {
                    stat.bindNull(6);
                } else {
                    stat.bindString(6,
                            recordArray.getJSONObject(i).get("isException")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) recordArray.getJSONObject(
                        i).get("planDate"))) {
                    stat.bindNull(7);
                } else {
                    stat.bindString(7,
                            recordArray.getJSONObject(i).get("planDate")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) recordArray.getJSONObject(
                        i).get("endTime"))) {
                    stat.bindNull(8);
                } else {
                    stat.bindString(8,
                            recordArray.getJSONObject(i).get("endTime")
                                    .toString());
                }
                if (TextUtils.isEmpty((CharSequence) recordArray.getJSONObject(
                        i).get("startTime"))) {
                    stat.bindNull(9);
                } else {
                    stat.bindString(9,
                            recordArray.getJSONObject(i).get("startTime")
                                    .toString());
                }
                // 根据is_exception字段是否为空判断is_download字段是否为下载的数据
                if (TextUtils.isEmpty((CharSequence) recordArray.getJSONObject(
                        i).get("isException"))) {
                    stat.bindString(10, "0");
                } else {
                    stat.bindString(10, "1");
                }
                stat.executeInsert();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        db.setTransactionSuccessful();
        db.endTransaction();
    }

    // 实现数据下载
    private class DownloadData extends AsyncTask<Void, Integer, String> {

        private Context context;
        private ProgressDialog prdlg;
        private AsyncResponse asyncResponse;

        private void setOnAsyncResponse(AsyncResponse asyncResponse) {
            this.asyncResponse = asyncResponse;
        }

        private DownloadData(Context context) {
            this.context = context;
            prdlg = new ProgressDialog(context);
            prdlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置进度条风格，风格为圆形，旋转的
            // 设置点击进度对话框外的区域对话框不消失
            prdlg.setCanceledOnTouchOutside(false);
            prdlg.setMessage("加载点检任务中，请等待...");
        }

        @Override
        protected void onPreExecute() {
            Log.i(TAG, "onPreExecute() called");
            prdlg.show();
        }

        // onProgressUpdate方法用于更新进度信息
        @Override
        protected void onProgressUpdate(Integer... progresses) {
            Log.i(TAG, "onProgressUpdate(Progress... progresses) called");
            // prdlg.setMessage("Loading. Please wait..." + progresses[0]);
        }

        @Override
        protected String doInBackground(Void... params) {
            Log.i(TAG, "doInBackground(Params... params) called");
            HttpURLConnection oConn = null;
            String reqUrl = GlobalVar.httpUrl + "checkRecord/queryAppList";
            String result = null;
            try {
                URL oUrl = new URL(reqUrl);
                oConn = (HttpURLConnection) oUrl.openConnection();
                oConn.setConnectTimeout(5000);
                if (oConn != null) {
                    String sessionId = SharedPreferencesUtils
                            .getSessionId(context);
                    oConn.setRequestProperty("cookie", "JSESSIONID="
                            + sessionId);
                    oConn.setRequestProperty("Accept-Encoding", "identity");
                    BufferedReader oIn = new BufferedReader(
                            new InputStreamReader(oConn.getInputStream()));
                    if (null != oIn) {
                        result = oIn.readLine();
                        oIn.close();
                    }
                    return result;
                    // 其它方式下载
                    // InputStream is= oConn.getInputStream();
                    // long total = is.read();
                    // Log.i(TAG, total+"后台数据的大小******");
                    // prdlg.setMax((int)(total));
                    // ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    // byte[] buf = new byte[10240];
                    // int count = 0;
                    // int length = -1;
                    // while ((length = is.read(buf)) != -1) {
                    // baos.write(buf, 0, length);
                    // count += length;
                    // // 调用publishProgress公布进度,最后onProgressUpdate方法将被执行
                    // publishProgress((int) ((count / (float) total) * 100));
                    // Thread.sleep(500);
                    // }
                    // return new String(baos.toByteArray(), "utf-8");
                }

                // HttpClient client = new DefaultHttpClient();
                // HttpPost req = new HttpPost(params[0]);
                // String sessionId =
                // SharedPreferencesUtils.getSessionId(context);
                // req.setHeader("Cookie", "JSESSIONID="+sessionId);
                // HttpResponse response = client.execute(req);
                // if (response.getStatusLine().getStatusCode() ==
                // HttpStatus.SC_OK) {
                // HttpEntity entity = response.getEntity();
                // InputStream is = entity.getContent();
                // long total = entity.getContentLength();
                // Log.i(TAG, total+"后台数据的大小******");
                // prdlg.setMax((int)(total));
                // ByteArrayOutputStream baos = new ByteArrayOutputStream();
                // byte[] buf = new byte[10240];
                // int count = 0;
                // int length = -1;
                // while ((length = is.read(buf)) != -1) {
                // baos.write(buf, 0, length);
                // count += length;
                // // 调用publishProgress公布进度,最后onProgressUpdate方法将被执行
                // publishProgress((int) ((count / (float) total) * 100));
                // Thread.sleep(500);
                // }
                // return new String(baos.toByteArray(), "utf-8");
                // }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
            return null;
        }

        // onPostExecute方法用于在执行完后台任务后更新UI,显示结果
        @Override
        protected void onPostExecute(String result) {
            Log.i(TAG, "onPostExecute(Result result) called");
            prdlg.setMessage("数据下载完毕，正在进入数据处理");
            prdlg.dismiss();
            if (result != null) {
                asyncResponse.onDataReceivedSuccess(result);
            } else {
                asyncResponse.onDataReceivedFailed();
            }
        }

        // onCancelled方法用于在取消执行中的任务时更改UI
        @Override
        protected void onCancelled() {
            Log.i(TAG, "onCancelled() called");
            super.onCancelled();
        }
    }

    // 实现页面滑动
    @SuppressLint("NewApi")
    private void setUpActionBar() {
        final ActionBar actionBar = getActionBar();
        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setDisplayShowHomeEnabled(false);
    }

    // 实现页面滑动
    private void setUpViewPager() {
        mViewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mViewPagerAdapter);
        mViewPager
                .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                    @Override
                    public void onPageSelected(int position) {
                        final ActionBar actionBar = getActionBar();
                        actionBar.setSelectedNavigationItem(position);
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {
                        switch (state) {
                            case ViewPager.SCROLL_STATE_IDLE:
                                break;
                            case ViewPager.SCROLL_STATE_DRAGGING:
                                break;
                            case ViewPager.SCROLL_STATE_SETTLING:
                                break;
                            default:
                                break;
                        }
                    }
                });
    }

    // 实现页面滑动
    private void setUpTabs() {
        final ActionBar actionBar = getActionBar();
        for (int i = 0; i < mViewPagerAdapter.getCount(); ++i) {
            actionBar.addTab(actionBar.newTab()
                    .setText(mViewPagerAdapter.getPageTitle(i))
                    .setTabListener(this));
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (!supportScan) {
            return;
        }
        if ("sc".equals(GlobalVar.scanType)) {
            GlobalVar.sc.interrupt();
            GlobalVar.sc.close();
        } else {
            GlobalVar.ct.stopPort();
        }
    }

    // 实现页面滑动
    public class ViewPagerAdapter extends FragmentPagerAdapter {

        public ViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case TAB_INDEX_ONE:
                    return ckc;
                case TAB_INDEX_TWO:
                    return dck;
                case TAB_INDEX_THREE:
                    return wis;
            }
            throw new IllegalStateException("No fragment at position "
                    + position);
        }

        @Override
        public int getCount() {
            return TAB_INDEX_COUNT;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            String tabLabel = null;
            switch (position) {
                case TAB_INDEX_ONE:
                    tabLabel = getString(R.string.checkclazz);
                    break;
                case TAB_INDEX_TWO:
                    tabLabel = getString(R.string.dailycheck);
                    break;
                case TAB_INDEX_THREE:
                    tabLabel = getString(R.string.weekinspection);
                    break;
            }
            return tabLabel;
        }
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub
        Log.i(TAG, "*********onTabSelected:" + tab.getPosition());
        // 获取当前frament碎片的ID
        frament = tab.getPosition();
        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub
        Log.i(TAG, "*********onTabUnselected:" + tab.getPosition());
    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
        // TODO Auto-generated method stub
        Log.i(TAG, "*********onTabReselected:" + tab.getPosition());
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public Handler getHandler() {
        Handler handler = this.myHandler2;
        return handler;
    }

    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(this).setTitle("你确定要退出吗!")
                .setIcon(android.R.drawable.ic_dialog_info)
                .setCancelable(false)
                .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .setNegativeButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                        System.exit(0);
                    }
                }).show();
    }
}
